package com.google.code.p.restrpc.client.registry;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.google.code.p.restrpc.client.RpcOptionsFactory;
import com.google.code.p.restrpc.client.proxy.RpcProxyFactory;
import com.google.code.p.restrpc.directory.RemoteServiceDefinitionPack;
import com.google.code.p.restrpc.directory.service.DirectoryService;

/**
 * @author dz
 */
public class DefaultRegistryClientFactory implements RegistryClientFactory {
    
    private static final Log logger = LogFactory.getLog(DefaultRegistryClientFactory.class);
    
    private String directoryServiceUrl;
    
    /**
     * global default directoryServiceUrl (specified in restrpc.client.properties) will be used
     */
    public DefaultRegistryClientFactory() {
        this.directoryServiceUrl = RpcOptionsFactory.getInstance()
                                                    .getDirectoryServiceUrl();
    }
    
    /**
     * 
     * @param directoryServiceUrl
     */
    public DefaultRegistryClientFactory(String directoryServiceUrl) {
        this.directoryServiceUrl = directoryServiceUrl;
    }
    
    /**
     * @return
     */
    public RegistryClient getRegistryClient() {
        if (StringUtils.isEmpty(directoryServiceUrl)) {
            throw new IllegalArgumentException("The default directoryServiceUrl is null or empty!");
        }
        return getRegistryClient(directoryServiceUrl);
    }
    
    public RegistryClient getRegistryClient(String directoryServiceUrl) {
        if (StringUtils.isEmpty(directoryServiceUrl)) {
            throw new IllegalArgumentException("The 'directoryServiceUrl' can't be null or empty!");
        }
        
        final DirectoryService directoryService = RpcProxyFactory.getInstance()
                                                                 .createProxy(DirectoryService.class,
                                                                              directoryServiceUrl);
        
        return new RegistryClient() {
            
            public RemoteServiceDefinitionPack lookup(String serviceName,
                                                      long lastModifiedMillis) {
                if (StringUtils.isEmpty(serviceName)) {
                    throw new IllegalArgumentException("serviceName can't be null or empty!");
                }
                
                RemoteServiceDefinitionPack result = directoryService.lookup(serviceName,
                                                                             lastModifiedMillis);
                if (logger.isDebugEnabled()) {
                    logger.debug("Lookup Result:" + result);
                }
                return result;
            }
            
        };
    }
}
